// 导入模块
const api = require('../../api/api.js')

Page({
  data: {
    types:[] // 所有分类电影信息
  },
  goSearch(){
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  onReady(){
    // 将数据存储本地缓存，避免多次向豆瓣发请求
    let types = wx.getStorageSync('types')
    if(types && types.length!=0){
      return this.setData({types})
    }
    
    Promise.all([
      this.loadHotFilms(),
      this.loadLatestFilms(),
      this.loadFreeFilms(),
    ]).then(() => {
      console.log(this.data.types)
      wx.setStorageSync('types', this.data.types)
    })
  },
  // 加载影院热映
  loadHotFilms(){
    return api.loadHotFilms({
      start: 0,
      count: 6
    }).then(res => {
      let type = {
        title: res.subject_collection.name,
        list: res.subject_collection_items,
        method: res.method
      }
      this.setData({
        'types[0]': type
      })
    })
  },
  // 加载近期热门
  loadLatestFilms(){
    return api.loadLatestFilms({
      start: 0,
      count: 6
    }).then(res => {
      let type = {
        title: res.subject_collection.name,
        list: res.subject_collection_items,
        method: res.method
      }
      this.setData({
        'types[1]': type
      })
    })
  },
  // 加载免费在线
  loadFreeFilms(){
    return api.loadFreeFilms({
      start: 0,
      count: 6
    }).then(res => {
      let type = {
        title: res.subject_collection.name,
        list: res.subject_collection_items,
        method: res.method
      }
      this.setData({
        'types[2]': type
      })
    })
  }
  
})